import Taro, { onSocketOpen, SocketTask } from '@tarojs/taro';
import { getTokenWithAuth } from './tokens';

export const wssUrl = 'wss://www.liuzhiwei.xyz:4001/socket.io/?EIO=3&transport=websocket';
export const wssUrl2 = 'wss://www.liuzhiwei.xyz:4001/socket.io/?EIO=3&transport=websocket';
/**
 * 链接
 * @returns
 */
export async function socketConnect(): Promise<SocketTask> {
  return await Taro.connectSocket({
    url: wssUrl,
    header: {
      'content-type': 'application/json',
      Authorization: getTokenWithAuth(),
    },
  });
}

export function socketOpen(fun: any) {
  onSocketOpen(fun);
}

/**
 * 初始化socket链接
 */
export async function initSocket() {
  const tasks = await socketConnect();

  return tasks;
}

export async function sendMessage(data: unknown) {
  const options: SendOption = {
    data: data as string | ArrayBuffer,
    success: () => {
      console.log('发送成功');
    },
  };
  Taro.sendSocketMessage(options);
}

/**
 * 关闭连接
 */
export async function socketClose() {
  // const options:Option = {

  // }
  await Taro.closeSocket();

  // console.log('关闭成功 ');
}

// types ===============
export interface SendOption {
  /** 需要发送的内容 */
  data: string | ArrayBuffer;
  /** 接口调用结束的回调函数（调用成功、失败都会执行） */
  complete?: (res: TaroGeneral.CallbackResult) => void;
  /** 接口调用失败的回调函数 */
  fail?: (res: TaroGeneral.CallbackResult) => void;
  /** 接口调用成功的回调函数 */
  success?: (res: TaroGeneral.CallbackResult) => void;
}
